package com.shxzz.shortlink.admin.common.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.shxzz.shortlink.admin.common.convention.errorcode.BaseErrorCode;
import com.shxzz.shortlink.admin.common.convention.exception.BaseException;
import com.shxzz.shortlink.admin.common.convention.exception.ServiceException;
import com.shxzz.shortlink.admin.common.convention.result.Result;
import com.shxzz.shortlink.admin.common.convention.result.Results;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.annotation.Annotation;
import java.util.Optional;

/**
 * @author shxzz
 * @create 2023-12-09-14:58
 * @description 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 错误日志格式模板
     */
    public static final String ERROR_LOG_FORMAT = "[{}] {} [ex] {}";

    /**
     * 处理参数验证异常
     */
    @SneakyThrows
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<Void> validExceptionHandler(HttpServletRequest request, MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();

        FieldError firstFieldError = CollUtil.getFirst(bindingResult.getFieldErrors());

        String exceptionStr = Optional.ofNullable(firstFieldError)
                .map(FieldError::getDefaultMessage)
                .orElse(CharSequenceUtil.EMPTY);

        log.error(ERROR_LOG_FORMAT, request.getMethod(), getUrl(request), exceptionStr);

        return Results.failure(BaseErrorCode.CLIENT_ERROR.getCode(), exceptionStr);
    }

    /**
     * 处理应用内抛出的异常
     */
    @ExceptionHandler(value = BaseException.class)
    public Result<Void> baseExceptionHandler(HttpServletRequest request, BaseException ex) {
        if (ex.getCause() != null) {
            log.error(ERROR_LOG_FORMAT, request.getMethod(), request.getRequestURL().toString(), ex, ex.getCause());
            return Results.failure(ex);
        }

        log.error(ERROR_LOG_FORMAT, request.getMethod(), request.getRequestURL().toString(), ex.toString());

        return Results.failure(ex);
    }

    /**
     * 处理未知异常
     */
    @ExceptionHandler(value = Throwable.class)
    public Result<Void> defaultExceptionHandler(HttpServletRequest request, Throwable throwable) {
        log.error("[{}] {} ", request.getMethod(), getUrl(request), throwable);

        return Results.failure();
    }

    /**
     * 获取请求url
     */
    private String getUrl(HttpServletRequest request) {

        if (StringUtils.hasLength(request.getQueryString())) {
            return request.getRequestURL().toString();
        }
        return request.getRequestURL().toString() + "?" + request.getQueryString();
    }

}
